/*
 * @Description:
 * @Author: Rfan
 * @Date: 2022-06-28 20:35:00
 * @LastEditTime: 2022-06-30 13:49:05
 */

import { Key, useEffect, useState } from 'react';
import { Button, Form, Modal } from 'antd';
import type { FC } from 'react';
import { useFolderTreeContext } from '../../../contexts/FolderTreeContext';
import DictionarySetting from './components/DictionarySetting';
import GeneralSetting from './components/GeneralSetting';
import type { ICommonDialog } from '@/interfaces/global';
import type { IMetadata } from '@/interfaces/metadata';

interface DataSettingDialogProps extends ICommonDialog {
  type: number;
  field: IMetadata;
}

const DataSettingDialog: FC<DataSettingDialogProps> = (props) => {
  const { visible, field, type, onClose } = props;
  const { groupPlanAddProp } = useFolderTreeContext();
  const [genForm] = Form.useForm();

  // 字典表格选中的条目
  const [selectItems, setSelectedItem] = useState<Key[]>([]);

  useEffect(() => {
    if (visible) {
      //
    }
  }, [visible]);

  /**
   * @description: 关闭弹窗方法
   */
  const onCancel = () => {
    onClose();
  };

  const saveDataSetting = () => {
    if (type === 1) {
      console.log('dic', selectItems, type);
      const ruleConfig = {
        ruleType: type,
        dictList: selectItems
      };
      groupPlanAddProp(field, 'ruleConfig', ruleConfig);
      groupPlanAddProp(field, 'configRule', true);
      onClose();
    } else {
      genForm.submit();
    }
  };

  return (
    <Modal
      title="数据设置"
      visible={visible}
      width={500}
      destroyOnClose
      onCancel={onCancel}
      footer={[
        <Button key="close" onClick={onCancel}>
          关闭
        </Button>,
        <Button
          key="save"
          type="primary"
          onClick={() => {
            saveDataSetting();
          }}
        >
          保存
        </Button>
      ]}
    >
      {type === 1 ? (
        <DictionarySetting field={field} setSelectedItem={setSelectedItem} />
      ) : (
        <GeneralSetting form={genForm} type={type} field={field} onClose={onClose} />
      )}
    </Modal>
  );
};

export default DataSettingDialog;
